﻿using System.Windows.Media;
using ICSharpCode.AvalonEdit.Editing;
using ICSharpCode.AvalonEdit.Rendering;

namespace ICSharpCode.AvalonEdit.Highlighting
{
    public class HighlightCurrentLineBackgroundRenderer : IBackgroundRenderer
    {
        private readonly TextArea _textArea;

        public HighlightCurrentLineBackgroundRenderer(TextArea textArea)
        {
            _textArea = textArea;
            _textArea.SelectionChanged +=
                (sender, args) =>
                    {
                        _textArea.Caret.Show();
                        _textArea.TextView.InvalidateLayer(KnownLayer.Background);
                    };
            _textArea.Caret.PositionChanged +=
                (sender, args) => _textArea.TextView.InvalidateLayer(KnownLayer.Background);
        }

        public KnownLayer Layer
        {
            get { return KnownLayer.Caret; }
        }

        public void Draw(TextView textView, DrawingContext drawingContext)
        {
            if (_textArea.Document == null || !_textArea.ShowCurrentLine)
                return;

            if (_textArea.HideCurrentLineWhenTextSelected && _textArea.Selection.Length > 0)
                return;
            
            var geoBuilder = new BackgroundGeometryBuilder
                {
                    AlignToMiddleOfPixels = true,
                    CornerRadius = _textArea.CurrentLineCornerRadius
                };

            textView.EnsureVisualLines();
            var currentLine = _textArea.Document.GetLineByOffset(_textArea.Caret.Offset);
            foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(textView, currentLine))
            {
                geoBuilder.AddRectangle(rect.Left, rect.Top, textView.ActualWidth + textView.ScrollOffset.X, rect.Top + rect.Height);
            }
            
            //geoBuilder.AddSegment(textView, currentLine);
            var geometry = geoBuilder.CreateGeometry();
            if (geometry != null)
            {
                drawingContext.DrawGeometry(_textArea.CurrentLineBrush, _textArea.CurrentLineBorder, geometry);
            }
            /*
            textView.EnsureVisualLines();
            var currentLine = _textArea.Document.GetLineByOffset(_textArea.Caret.Offset);
            foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(textView, currentLine))
            {
                drawingContext.DrawRectangle(
                    _textArea.CurrentLineBrush, _textArea.CurrentLineBorder,
                    new Rect(rect.Location, new Size(textView.ActualWidth + textView.ScrollOffset.X, rect.Height)));
            }
             */
        }
    }
}
